<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

// 查询参数
const dateRange = ref({
  start: new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000),
  end: new Date()
})
const operator = ref('ALL')
const networkType = ref('ALL')

// 选项数据
const operatorOptions = ['ALL', 'CMCC', 'CUCC', 'CTCC']
const networkTypeOptions = ['ALL', '4G', '3G', '2G']

// 图表引用
const barChartRef = ref<HTMLElement | null>(null)
const pieChartRef = ref<HTMLElement | null>(null)
let barChart: echarts.ECharts | null = null
let pieChart: echarts.ECharts | null = null

// 初始化图表
const initCharts = () => {
  if (barChartRef.value && !barChart) {
    barChart = echarts.init(barChartRef.value)
  }
  if (pieChartRef.value && !pieChart) {
    pieChart = echarts.init(pieChartRef.value)
  }
}

const fetchChartData = async () => {
  try {
    // 获取柱状图数据
    const barResponse = await axios.get('/api/app/traffic-rank', {})

    // 获取饼图数据
    const pieResponse = await axios.get('/api/app/traffic-pie', {})

    // 设置柱状图配置
    const barOption: echarts.EChartsOption = {
       title: {
              text: '热门APP流量排名',
              top: 10
       },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      legend: {
        data: barResponse.data.data.legends,
        top: 30
      },
      grid: {
        top: '15%',
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: barResponse.data.data.xAxisData,
        axisLabel: {
          interval: 0,
          rotate: 0,
          textStyle: {
            fontSize: 12
          }
        }
      },
      yAxis: {
        type: 'value',
        name: '单位(GB)'
      },
      series: barResponse.data.data.legends.map((legend: string, index: number) => ({
        name: legend,
        type: 'bar',
        data: barResponse.data.data.seriesData[index],
        label: { show: false },
        emphasis: {
          label: {
            show: true,
            position: 'top',
            formatter: '{c} GB',
            fontSize: 12,
            color: '#333'
          }
        },
      }))
    }

    // 设置饼图配置
    const pieOption: echarts.EChartsOption = {
      title: {
        text: '热门APP排名',
        left: 'center',
        top: 10
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} GB ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        top: 40,
        itemWidth: 10,
        itemHeight: 10,
        textStyle: {
          fontSize: 12
        }
      },
      series: [{
        name: 'APP流量',
        type: 'pie',
        radius: ['0%', '60%'],
        center: ['60%', '55%'],
        data: pieResponse.data.data.names.map((name: string, index: number) => ({
          name,
          value: pieResponse.data.data.values[index],
          itemStyle: {
            color: pieResponse.data.data.colors[index]
          }
        })),
        label: {
          show: true,
          formatter: '{b}',
          fontSize: 12,
          position: 'outside'
        },
        labelLine: {
          length: 10,
          length2: 10,
          smooth: true
        },
        emphasis: {
          label: {
            show: true,
            formatter: '{b}: {d}%',
            fontSize: 14,
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    }

    // 更新图表
    if (barChart) barChart.setOption(barOption)
    if (pieChart) pieChart.setOption(pieOption)
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 生命周期钩子
onMounted(async () => {
  await nextTick()  // 等待 DOM 更新
  initCharts()      // 初始化图表
  fetchChartData()  // 获取数据
  window.addEventListener('resize', handleResize)
})

// 处理窗口大小变化
const handleResize = () => {
  barChart?.resize()
  pieChart?.resize()
}

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (barChart) {
    barChart.dispose()
    barChart = null
  }
  if (pieChart) {
    pieChart.dispose()
    pieChart = null
  }
})

// 监听网络制式变化
watch(networkType, () => {
  fetchChartData()
})
</script>

<template>
  <div class="app-traffic-rank">
    <div class="mb-4 query-panel">
      <div class="flex flex-wrap items-end gap-4">
        <div class="query-item">
          <label>日期范围</label>
          <VaDateInput v-model="dateRange" mode="range" placeholder="选择日期范围" />
        </div>

        <div class="query-item">
          <label>运营商</label>
          <VaSelect v-model="operator" :options="operatorOptions" />
        </div>

        <div class="query-item">
          <label>网络制式</label>
          <VaSelect v-model="networkType" :options="networkTypeOptions" />
        </div>

        <VaButton type="primary" @click="fetchChartData">查询</VaButton>
      </div>
    </div>

    <div class="grid grid-cols-5 gap-4 charts-container">
      <div ref="barChartRef" class="col-span-3 chart-box" style="height: calc(100vh - 280px)"></div>
      <div ref="pieChartRef" class="col-span-2 chart-box" style="height: calc(100vh - 280px)"></div>
    </div>
  </div>
</template>

<style scoped>
.app-traffic-rank {
  padding: 16px;
}

.query-panel {
  background: white;
  padding: 12px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.charts-container {
  margin-top: 12px;
}

.chart-box {
  background: white;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  height: 450px;
}

.query-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.query-item label {
  font-size: 14px;
  color: #666;
}

.va-select {
  width: 180px;
}

.va-date-input {
  width: 220px;
}
</style>
